var interval, autoSubmit, autoBuy, autoConfirm, autoCart, autoSubmit, autoPay, autoSku, autoCoupon, checkPrice, maxPrice;
var itemName;
//存储
var storage = storages.create("tb_live_qg.js");

//时间工具类
var timeUtils = require('TimeUtils.js');
var window = floaty.window(
    <frame>
        <vertical w="auto" h="auto" background='#66000000' gravity="center">
            <text id="title" text="直播助手" gravity="top|center" textColor="red" textSize="13sp" margin="0 5" />
            <frame w="*" margin="12" h="1" bg="#e3e3e3" />
            <horizontal>
                <checkbox id="autoBuy" text="辅助抢购  " textColor="white" />
                <checkbox id="autoConfirm" text="辅助确认 " textColor="white" />
            </horizontal>
            <horizontal>
                <checkbox id="autoCart" text="辅助结算  " textColor="white" />
                <checkbox id="autoSubmit" text="辅助提交  " textColor="white" />
            </horizontal>
            <horizontal>
                <checkbox id="autoSku" text="自动SKU   " textColor="white" />
                <checkbox id="autoCoupon" text="自动领劵  " textColor="white" />
            </horizontal>
            <horizontal >
                <checkbox id="lockItem" text="指定商品:" textColor="white" />
                <input id="itemName" text="" hint="袋鼠医用" focusable="true" textColor="red" textSize="14sp" />
            </horizontal>
            <horizontal >
                <checkbox id="checkPrice" text="限制价格:" textColor="white" />
                <input id="maxPrice" text="" hint="10" focusable="true" textColor="black" textSize="14sp" />
            </horizontal>
            <horizontal >
                <text text="  提交频率(毫秒)：" gravity="top|left" textColor="white" />
                <input id="interval" text="100" hint="无" focusable="true" textColor="black" textSize="14sp" />
            </horizontal>
            <frame w="*" margin="12" h="1" bg="#e3e3e3" />
            <horizontal gravity="top|center">
                <button id="runButton" style="Widget.AppCompat.Button.Colored" text="开始" w="auto" h="*" />
                <button id="stopUi" style="Widget.AppCompat.Button.Colored" text="退出" w="auto" h="*" />
            </horizontal>
        </vertical>
    </frame>
);


window.setPosition(device.width / 2 - 400, device.width / 2 - 400);
window.exitOnClose();

window.title.on("click", () => {
    //开启位置调整
    window.setAdjustEnabled(!window.isAdjustEnabled());
});

window.itemName.on("touch_down", () => {
    window.requestFocus();
    window.itemName.requestFocus();
});

window.maxPrice.on("touch_down", () => {
    window.requestFocus();
    window.maxPrice.requestFocus();
});

window.interval.on("touch_down", () => {
    window.requestFocus();
    window.interval.requestFocus();
});

//检查价格设置
window.checkPrice.on("check", function (checked) {
    // 用户勾选价格校验
    if (checked) {
        // exectuion = engines.execScriptFile("time.js");
        if (!window.maxPrice.text()) {
            window.checkPrice.checked = false;
            logError("限制金额的最高金额必须填写！！！");
        }
    }
});

//检查价格设置
window.lockItem.on("check", function (checked) {
    // 用户勾选价格校验
    if (checked) {
        // exectuion = engines.execScriptFile("time.js");
        if (!window.itemName.text()) {
            window.lockItem.checked = false;
            logError("指定商品名称必须填写！！！");
        }
    }
});

//退出
window.stopUi.on("click", () => {
    console.hide();
    window.close();
    floaty.closeAll();
    threads.shutDownAll();
    exit();
});


//*******************************************************************基础方法***************************************************************************************** */
//打开浮窗
function openConsole() {
    auto.waitFor()
    //显示控制台
    var middle = device.width / 2 - 400;
    console.setSize(800, 800);
    console.setPosition(middle, 0);
    console.show();
}

// 时间戳转时间字符串
function add0(m) {
    return m < 10 ? '0' + m : m
}

function add00(m) {
    if (m < 10) {
        return '00' + m;
    } else if (m < 100) {
        return '0' + m;
    } else {
        return m;
    }
}

function formatDate(needTime) {
    //needTime是整数，否则要parseInt转换
    var time = new Date(parseInt(needTime));
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    var ms = time.getMilliseconds();
    return add0(h) + ':' + add0(mm) + ':' + add0(s) + ":" + add00(ms);
}

// 根据时间偏移值计算真实时间
function getNow() {
    var now = new Date().getTime();
    return now;
}

//*******************************************************************基础方法***************************************************************************************** */
//*******************************************************************滑动方法***************************************************************************************** */

/**
 * 真人模拟滑动函数
 * 
 * 传入值：起点终点坐标
 * 效果：模拟真人滑动
 */
function randomSwipe(sx, sy, ex, ey) {
    //设置随机滑动时长范围
    var timeMin = 1000
    var timeMax = 3000
    //设置控制点极限距离
    var leaveHeightLength = 500

    //根据偏差距离，应用不同的随机方式
    if (Math.abs(ex - sx) > Math.abs(ey - sy)) {
        var my = (sy + ey) / 2
        var y2 = my + random(0, leaveHeightLength)
        var y3 = my - random(0, leaveHeightLength)

        var lx = (sx - ex) / 3
        if (lx < 0) { lx = -lx }
        var x2 = sx + lx / 2 + random(0, lx)
        var x3 = sx + lx + lx / 2 + random(0, lx)
    } else {
        var mx = (sx + ex) / 2
        var y2 = mx + random(0, leaveHeightLength)
        var y3 = mx - random(0, leaveHeightLength)

        var ly = (sy - ey) / 3
        if (ly < 0) { ly = -ly }
        var y2 = sy + ly / 2 + random(0, ly)
        var y3 = sy + ly + ly / 2 + random(0, ly)
    }

    //获取运行轨迹，及参数
    var time = [0, random(timeMin, timeMax)]
    var track = bezierCreate(sx, sy, x2, y2, x3, y3, ex, ey)

    // log("随机控制点A坐标：" + x2 + "," + y2)
    // log("随机控制点B坐标：" + x3 + "," + y3)
    // log("随机滑动时长：" + time[1])

    // log("time:"+time)
    // log("track:"+track)
    //滑动
    gestures(time.concat(track))
}


function bezierCreate(x1, y1, x2, y2, x3, y3, x4, y4) {
    //构建参数
    var h = 100;
    var cp = [{ x: x1, y: y1 + h }, { x: x2, y: y2 + h }, { x: x3, y: y3 + h }, { x: x4, y: y4 + h }];
    var numberOfPoints = 100;
    var curve = [];
    var dt = 1.0 / (numberOfPoints - 1);

    //计算轨迹
    for (var i = 0; i < numberOfPoints; i++) {
        var ax, bx, cx;
        var ay, by, cy;
        var tSquared, tCubed;
        var result_x, result_y;

        cx = 3.0 * (cp[1].x - cp[0].x);
        bx = 3.0 * (cp[2].x - cp[1].x) - cx;
        ax = cp[3].x - cp[0].x - cx - bx;
        cy = 3.0 * (cp[1].y - cp[0].y);
        by = 3.0 * (cp[2].y - cp[1].y) - cy;
        ay = cp[3].y - cp[0].y - cy - by;

        var t = dt * i
        tSquared = t * t;
        tCubed = tSquared * t;
        result_x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
        result_y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
        curve[i] = {
            x: result_x,
            y: result_y
        };
    }

    //轨迹转路数组
    var array = [];
    for (var i = 0; i < curve.length; i++) {
        try {
            var j = (i < 100) ? i : (199 - i);
            xx = parseInt(curve[j].x)
            yy = parseInt(Math.abs(100 - curve[j].y))
        } catch (e) {
            break
        }
        array.push([xx, yy])
    }

    return array
}
//*******************************************************************滑动方法***************************************************************************************** */
//*******************************************************************日志处理***************************************************************************************** */
// 获取时分秒用于记录日志
function logCommon(msg) {
    console.log(formatDate(getNow()) + " " + msg);
}
function logInfo(msg) {
    console.info(formatDate(getNow()) + " " + msg);
}
function logWarn(msg) {
    console.warn(formatDate(getNow()) + " " + msg);
}
function logError(msg) {
    console.error(formatDate(getNow()) + " " + msg);
}

//*******************************************************************日志处理***************************************************************************************** */
//*******************************************************************初始化设置***************************************************************************************** */
function initConfig() {
    ui.run(function () {
        //商品名称
        window.itemName.setText(storage.get("itemName", "").toString());

        window.autoBuy.checked = storage.get("autoBuy", true);
        window.autoConfirm.checked = storage.get("autoConfirm", true);
        window.autoCart.checked = storage.get("autoCart", true);
        window.autoSubmit.checked = storage.get("autoSubmit", true);

        window.lockItem.checked = storage.get("lockItem", false);
        window.autoSku.checked = storage.get("autoSku", false);

        window.autoCoupon.checked = storage.get("autoCoupon", false);

        //校验价格
        window.checkPrice.checked = false;
        //最高价格
        window.maxPrice.setText("1");

        //提交频率
        window.interval.setText(storage.get("interval", "100").toString());
    });

}
//*******************************************************************初始化设置***************************************************************************************** */
//*******************************************************************主程序***************************************************************************************** */

//*******************************************************************主程序***************************************************************************************** */

//开始
window.runButton.on("click", () => {

    window.disableFocus();
    //准备参数

    //辅助购买
    autoBuy = window.autoBuy.checked;
    //辅助确认
    autoConfirm = window.autoConfirm.checked;
    //辅助结算
    autoCart = window.autoCart.checked;
    //辅助提交
    autoSubmit = window.autoSubmit.checked;

    lockItem = window.lockItem.checked;
    autoSku = window.autoSku.checked;

    autoCoupon = window.autoCoupon.checked;

    //商品名称
    itemName = window.itemName.text();

    //校验价格
    checkPrice = window.checkPrice.checked;
    //最高价格
    maxPrice = parseInt(window.maxPrice.getText());

    //提交订单频率 毫秒
    interval = parseInt(window.interval.getText());

    storage.put("autoBuy", autoBuy);
    storage.put("autoConfirm", autoConfirm);
    storage.put("autoCart", autoCart);
    storage.put("autoSubmit", autoSubmit);

    storage.put("lockItem", lockItem);
    storage.put("autoSku", autoSku);

    storage.put("autoCoupon", autoCoupon);

    storage.put("itemName", itemName);
    storage.put("interval", interval);

    //启动任务
    if (window.runButton.text() == "开始") {
        //保持屏幕常亮
        device.keepScreenOn();
        //开始任务
        threads.start(doJob);
        window.runButton.text("停止");
    } else {
        window.runButton.text("开始");
        logInfo("停止运行...");
        threads.start(function () {
            //关闭控制台
            // console.hide();
            device.cancelKeepingAwake();
            threads.shutDownAll();
        });
    }
});

//初始化数据
setTimeout(initConfig, 500);

//开启控制台
threads.start(openConsole);

logCommon("淘宝直播检测模式");
logCommon("请进入直播页面...");

if (!textContains("跟主播聊什么").exists()) {
    logCommon("未进入直播间，请前往");
}

var checkThread = threads.start(function () {
    //在新线程执行的代码
    // logCommon( "购物车导航");
    while (true) {
        if (!textContains("跟主播聊什么").exists()) {
            logCommon("未进入直播间，请前往");
            textContains("跟主播聊什么").findOne();
            logCommon("已进入直播间，请检查是否已配置好商品名称及SKU确认，并设置好购买价格，脚本将自动检测下单...");
        }
        sleep(1000);
    }
});

setInterval(() => { }, 1000);

//*******************************************************************主程序***************************************************************************************** */


/**
* 开始任务
*/
function doJob() {
    logInfo("开始运行...")

    var skuWorkers = [];

    var addCartThread = threads.start(function () {
        //在新线程执行的代码
        let buyNow;
        while (true) {
            // waitForActivity("");
            buyNow = id("taolive_showcase_item_add_cart").findOne();
            logInfo("有宝贝上架了...")
            if (!lockItem) {
                if (autoSku) {
                    killThreads(skuWorkers);
                    skuWorkers = makeSkuKill();
                }
                if (buyNow.clickable()) {
                    logInfo("立即抢购-a：" + buyNow.click());
                } else {
                    logInfo("立即抢购-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                }
            } else if (lockItem && textContains(itemName).exists()) {
                if (autoSku) {
                    killThreads(skuWorkers);
                    skuWorkerId = makeSkuKill();
                }
                if (buyNow.clickable()) {
                    logInfo("立即抢购-a：" + buyNow.click());
                } else {
                    logInfo("立即抢购-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                }
            } else {
                logError("不是目标商品...")
            }
            sleep(interval);
        }
    });



    if (autoCoupon) {
        threads.start(function () {
            let buyNow;
            while (true) {
                if (text("领取").exists()) {
                    buyNow = textContains("领取").findOne();
                    if (buyNow.clickable()) {
                        logCommon("领劵-at：" + buyNow.click());
                    } else {
                        logCommon("领劵-ats：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                    }
                } else if (desc("领取").exists()) {
                    buyNow = textContains("领取").findOne();
                    if (buyNow.clickable()) {
                        logCommon("领劵-ad：" + buyNow.click());
                    } else {
                        logCommon("领劵-ads：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                    }
                }
                sleep(interval);
            }
        });
    }

    if (autoBuy) {
        var buyThread = threads.start(function () {
            //在新线程执行的代码
            let buyNow;
            while (true) {
                // waitForActivity("");
                buyNow = textContains("立即购买").findOne();
                if (buyNow.clickable()) {
                    logCommon("立即购买-a：" + buyNow.click());
                } else {
                    logCommon("立即购买-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                }
                sleep(interval);
            }
        });
        var buyJuanThread = threads.start(function () {
            //在新线程执行的代码
            let buyNow
            while (true) {
                // waitForActivity("");
                buyNow = textContains("领劵购买").findOne();
                if (buyNow.clickable()) {
                    logCommon("领劵购买-a：" + buyNow.click());
                } else {
                    logCommon("领劵购买-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                }
                sleep(interval);
            }
        });
        var buyNowThread = threads.start(function () {
            //在新线程执行的代码
            let buyNow;
            while (true) {
                // waitForActivity("");
                buyNow = textContains("马上抢").findOne();
                if (buyNow.clickable()) {
                    logCommon("马上抢-a：" + buyNow.click());
                } else {
                    logCommon("马上抢-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                }
                sleep(interval);
            }
        });
        var buyIdThread = threads.start(function () {
            //在新线程执行的代码
            let buyNow;
            while (true) {
                // waitForActivity("");
                buyNow = id("buy").findOne();
                if (buyNow.clickable()) {
                    logCommon("马上购买-a：" + buyNow.click());
                } else {
                    logCommon("马上购买-as：" + click(buyNow.bounds().centerX(), buyNow.bounds().centerY()));
                }
                sleep(interval);
            }
        });
    }

    if (autoConfirm) {
        var readThread = threads.start(function () {
            //在新线程执行的代码
            let confirm;
            while (true) {
                //等待商品详情页
                // waitForActivity("android.app.Dialog");
                //查找确认
                // var confirm = className("android.widget.TextView").textContains("确定").findOne();
                confirm = textContains("确定").findOne();
                if (confirm.clickable()) {
                    logCommon("确定-a：" + confirm.click());
                } else {
                    logCommon("确定-as：" + click(confirm.bounds().centerX(), confirm.bounds().centerY()));
                }
                sleep(interval);
            }
        });
        var read2Thread = threads.start(function () {
            //在新线程执行的代码
            let confirm;
            while (true) {
                //等待商品详情页
                // waitForActivity("android.app.Dialog");
                //查找确认
                // var confirm = className("android.widget.TextView").textContains("确定").findOne();
                confirm = text("否").findOne();
                if (confirm.clickable()) {
                    logCommon("否-a：" + confirm.click());
                } else {
                    logCommon("否-as：" + click(confirm.bounds().centerX(), confirm.bounds().centerY()));
                }
                sleep(interval);
            }
        });
    }

    if (autoCart) {
        var cartThread = threads.start(function () {
            //在新线程执行的代码
            let cart;
            while (true) {
                // waitForActivity("");
                cart = textContains("结算(").findOne();
                if (cart.clickable()) {
                    logCommon("立即结算-a：" + cart.click());
                } else {
                    let selectAll = className("android.widget.CheckBox").desc("全选").enabled(true).checked(false).findOne();
                    logCommon("全选-a：" + selectAll.click());
                    continue;
                }
                sleep(interval);
            }
        });
    }

    if (autoSubmit) {
        var submitThread = threads.start(function () {
            //在新线程执行的代码
            let submit;
            while (true) {
                // waitForActivity("");
                submit = text("提交订单").findOne();
                if (checkPrice) {
                    text("小计: ").findOne().parent().children().forEach(child => {
                        let target = child.findOne(className("android.widget.TextView").textContains("￥"));
                        if (target != null) {
                            let itemPriceStr = parseInt(target.text().replace("￥", ""));
                            let priceStr = parseInt(itemPriceStr);
                            if (priceStr && (priceStr <= maxPrice)) {
                                if (submit.clickable()) {
                                    logCommon("提交订单-a：" + submit.click());
                                } else {
                                    logCommon("提交订单-as：" + click(submit.bounds().centerX(), submit.bounds().centerY()));
                                }
                                sleep(interval);
                            } else {
                                logError("商品价格：" + itemPriceStr + "，超过限制金额：￥" + maxPrice);
                                sleep(interval * 10);
                            }
                        }
                    });
                } else {
                    if (submit.clickable()) {
                        logCommon("提交订单-a：" + submit.click());
                    } else {
                        logCommon("提交订单-as：" + click(submit.bounds().centerX(), submit.bounds().centerY()));
                    }
                    sleep(interval);
                }
            }
        });
    }

    var sleepThread = threads.start(function () {
        //在新线程执行的代码
        while (true) {
            logCommon("被盾：" + textContains("休息会").findOne().text());
            var sleepScope = textContains("向右滑动验证").findOne().bounds();

            var sx = sleepScope.left + (sleepScope.bottom - sleepScope.top) / 2;
            var ex = sleepScope.right - (sleepScope.bottom - sleepScope.top) / 2;
            var y = sleepScope.top + (sleepScope.bottom - sleepScope.top) / 2;

            logCommon("开始滑动")
            randomSwipe(sx, y, ex, y);
            logCommon("滑动完成")
            sleep(100);
        }
    });

    var readThread = threads.start(function () {
        //在新线程执行的代码
        let readButton;
        while (true) {
            readButton = textContains("我知道了").findOne();
            log("被盾了：" + readButton.click());
            sleep(100);
        }
    });

    var successThread = threads.start(function () {
        //在新线程执行的代码
        let payButton;
        while (true) {
            payButton = textContains("立即付款").findOne();
            logError(timeUtils.getLogTime(), "下单成功");
            if (autoPay) {
                payButton.parent().click();
                logError(timeUtils.getLogTime(), "尝试支付...");
            }
            sleep(1000);
            threads.shutDownAll();
            return;
        }
    });

    //保持脚本运行
    setInterval(() => { }, 1000);
}




/**
* 退出商品详情页
*/
function itemDetailBack() {
    logCommon("退出商品详情页：" + className("android.widget.TextView").desc("返回").findOne().click());
}

/**
* sku页面
*/
function itemSkuBack() {
    logCommon("退出SKU页：" + id("btn_skucard_closecard").findOne().click());
}
/**
* 退出提交订单页面
*/
function submitBack() {
    logCommon("退出提交订单页：" + id("btn_back").findOne().click());
}

/**
* 查找商品
*/
function getItem(itemName) {
    logCommon("开始查找商品：" + itemName);
    var target;
    while (true) {
        if (textContains(itemName).exists()) {
            target = textContains(itemName).findOne();
            logInfo("找到" + target.text());
        } else {
            target = descContains(itemName).findOne();
            logInfo("找到" + target.desc());
        }
        if (target) {
            return target;
        } else {
            sleep(500);
        }
    }
}


//=======================================================sku=============================================================//
/**
 * 启动一次sku随机
 */
function makeSkuKill() {
    var skuWorkers = [];
    var id = threads.start(function () {
        var skus = ["尺码", "鞋码", "机身尺码", "存储容量", "网络类型", "口味", "颜色", "颜色分类", "机身颜色", "套餐类型", "化妆品净含量"];
        for (var i = 0; i < skus.length; i++) {
            var sku = skus[i];
            skuWorkers.push(skuKill(sku));
        }
    });
    skuWorkers.push(id);
    return skuWorkers;
}


/**
 * sku清除
 * @param {*} skuName 
 */
function skuKill(skuName) {
    var id = threads.start(function () {
        while (true) {
            if (textContains(skuName).exists()) {
                autoSelectSku(skuName);
                log("自动选择:" + skuName);
                break;
            }
            sleep(100);
        }
    });
    return id;
}


/**
 * 自动选sku
 * @param {*} skuName 
 */
function autoSelectSku(skuName) {
    text(skuName).findOne().parent().children().forEach(child => {
        var target = child.findOne(className("android.widget.RelativeLayout").clickable(true).selected(false));
        if (target != null) {
            target.click();
            return;
        }
    });
}

//=======================================================sku=============================================================//

function killThreads(skuWorkers) {
    if (skuWorkers) {
        for (var i = 0; i < skuWorkers.length; i++) {
            var skuWorker = skuWorkers[i];
            if (skuWorker) {
                skuWorker.interrupt();
            }
        }
    }
}